/**
 * Copyright (C), 2015-2018, 成都启迪信息技术有限公司
 * FileName: SmsReport
 * Author:   sjkyll
 * Date:     2018-11-21 14:27
 * Description:
 * <author>          <time>          <version>          <desc>
 * 作者姓名         修改时间           版本号            描述
 */
package com.cdqidi.smsservice.service;

import com.cdqidi.smsservice.dto.AjaxResult;
import com.cdqidi.smsservice.dto.Sms;
import com.cdqidi.smsservice.exception.ApiException;
import com.cdqidi.smsservice.util.DateUtil;
import com.cdqidi.smsservice.util.HttpUtil;
import com.cdqidi.smsservice.util.JdbcPaginationHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.message.BasicNameValuePair;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 〈一句话功能简述〉<br>
 *
 * @author sjkyll
 * @create 2018-11-21 14:27
 * @since 1.0.0
 */
@Slf4j
@Service
public class SmsReportService {

    private static final String zwUrl = "http://223.86.3.124:8082/typtInterface/sms/smsSend";
    private static final String wlUrl = "http://cf.51welink.com/submitdata/Service.asmx/Sm_GetRemain";
    private final HttpUtil httpUtil;
    private final JdbcTemplate jdbcTemplate;
    private final JavaMailSender javaMailSender ;
    @Value(value = "${spring.mail.username}")
    private String username;


    @Autowired
    public SmsReportService(HttpUtil httpUtil, JdbcTemplate jdbcTemplate,JavaMailSender javaMailSender) {
        this.httpUtil = httpUtil;
        this.jdbcTemplate = jdbcTemplate;
        this.javaMailSender = javaMailSender;
    }

    /**
     * 卓望的状态报告
     *
     * @param reqId
     * @return
     * @throws ApiException
     */
    public String getZwReport(String reqId) throws ApiException {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("appid", "307115023");
            map.put("smssn", reqId);
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(map);
            System.out.println("json: " + json);
            List<BasicNameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("MsgType", "QRY_SMS_RESULT"));
            list.add(new BasicNameValuePair("Data", json));
            return httpUtil.sendPost(zwUrl, list, false);
        } catch (IOException e) {
            throw new ApiException(AjaxResult.error(e.getMessage()));
        }
    }

    @Scheduled(cron = "0 0 10,16 * * ? ")
    public void getBalance() {
        String mailMsg=null;
        String sname = "dlcdqd02";
        String spwd = "wd7wCEA7znl7AtuUQO";
        String xml = getWlBalance(sname, spwd);
        Integer balance = parseXml(xml);
        if (null == balance) {
            log.info("账号: " + sname + ",返回值: " + xml);
        } else {
            log.info("账号: " + sname + ",余额: " + balance);
            mailMsg="账号： "+sname+",余额： "+(balance/100)+"元,";
        }
        sname = "dlcdqd01";
        spwd = "c0ROCkQP29hYCiVoWS";
        xml = getWlBalance(sname, spwd);
        balance = parseXml(xml);
        if (null == balance) {
            log.info("账号: " + sname + ",返回值: " + xml);
        } else {
            log.info("账号: " + sname + ",余额: " + balance);
            mailMsg+="账号： "+sname+",余额： "+(balance/100)+"元。";
        }
        final String msg = mailMsg;
        MimeMessagePreparator mp = (mimeMessage)->{
            log.info("msg: "+msg);
            mimeMessage.setHeader("X-Mailer","Microsoft Outlook Express 6.00.2900.2869");
            mimeMessage.setFrom(new InternetAddress(username));
            mimeMessage.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("273790253@qq.com"));
            mimeMessage.setSubject("微网通联账户余额（"+ DateUtil.getCurrentDate() +")");
            mimeMessage.setText("微网通联,"+msg);
        };
        try{
            javaMailSender.send(mp);
        }catch (MailException e){
            e.printStackTrace();
        }
    }

    /**
     * 获得微网通联的余额
     */
    private String getWlBalance(String sname, String spwd) {
        List<BasicNameValuePair> list = new ArrayList<>();
        list.add(new BasicNameValuePair("sname", sname));
        list.add(new BasicNameValuePair("spwd", spwd));
        list.add(new BasicNameValuePair("scorpid", ""));
        list.add(new BasicNameValuePair("sprdid", "1012818"));
        try {
            return httpUtil.sendPost(wlUrl, list, false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    private Integer parseXml(String xml) {
        try {
            SAXBuilder saxBuilder = new SAXBuilder();
            StringReader cmd_in_buffer = new StringReader(xml);
            Document doc = saxBuilder.build(cmd_in_buffer);
            Element root = doc.getRootElement();
            List<Element> list = root.getChildren();
            String name;
            String text;
            int state = 0;
            for (Element e : list) {
                name = e.getName();
                text = e.getTextTrim();
                if (name.equals("State")) {
                    state = Integer.parseInt(text);
                }
                if (state == 0) {
                    if (name.equals("Remain")) {
                        return Integer.parseInt(text);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Page<Sms> getSmsReport(String mobile, Pageable pageable) {
        String select = "r.dest_num,r.content,r.check_code,r.receive_time as sendTime,re.submit as sendSubmit,re.resp_id,rep.send as reportState,rep.receive_time as reportTime,r.sms_number";
        String sqlExceptSelect = "from kernel_receive_logs r left join kernel_submit_resp_logs re on r.auto_sn = re.auto_sn " +
                "left join kernel_report_logs rep on r.auto_sn = rep.auto_sn " +
                "where r.dest_num=? " +
                "order by r.receive_time desc,r.check_code,r.sms_number";
        return new JdbcPaginationHelper<Sms>().fetchPage(jdbcTemplate, select,sqlExceptSelect, new Object[]{mobile}, pageable,Sms.class);

    }
}